import sys
import threading
import time
import tkinter as tk
import tkinter.messagebox
import pygetwindow as gw

from Frame import showSlave

path = "./plugin/goodUi/tip.txt"

if sys.argv[1] == "noconsole":
    print = lambda **kwargs: ...

def UireadPip():
    global path
    r = ""
    try:
        with open(path, 'r') as f:
            r = f.read()
    except FileNotFoundError:
        path = "./tip.txt"
    with open(path, 'w') as f:
        f.write("")

    return r


class UiWindow:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("奴隶岛辅助窗口")
        self.root.lift()
        self.root.resizable(False, False)
        t = threading.Thread(target=self.check_window)
        t.daemon = True
        t.start()

    def command(self, Imperial_edict):
        command_arg = Imperial_edict.split(" ")
        command_name = command_arg[0]

        try:
            if Imperial_edict != "":
                print(Imperial_edict)

            if Imperial_edict == "close":
                self.root.title(Imperial_edict)
                self.root.destroy()
                return
            elif command_name == "slave":
                showSlave.ShowSlave(self.root).setUi()
                print("奴隶界面设置")
            elif command_name == "clear":
                j = self.root.children
                for k, v in j.items():
                    self.root.children[k].destroy()
            elif command_name == "rebot":
                self.root.destroy()

        except RuntimeError as e:
            tk.messagebox.showerror("RuntimeError:", f"执行命令{command_arg[0]}出现{e}")

        except Exception as e:
            tk.messagebox.showerror("未知的错误:", f"执行命令{command_arg[0]}出现{e}")

    def check_window(self):
        while 1:
            if self.root.state() == "normal":
                cmd_window_title = "奴隶岛cmd"  # cmd窗口的标题（可能需要根据实际情况修改）
                my_windows_title = "奴隶岛辅助窗口"  # 当前窗口界面（可能需要根据实际情况修改）

                try:
                    Imperial_edict: str = UireadPip()
                    self.command(Imperial_edict)

                    cmd_window = gw.getWindowsWithTitle(cmd_window_title)
                    mwindow = gw.getWindowsWithTitle(my_windows_title)
                    if len(mwindow) > 0:
                        mwindow = mwindow[0]
                        mwindow.show()

                    wid, hei = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
                    if len(cmd_window) > 0:
                        cwin = cmd_window[0]
                        cwin.activate()
                        top, right, left = cwin.top, cwin.right, cwin.left

                        # 创建Tkinter窗口
                        window_width = 400
                        window_height = 300

                        # 计算Tkinter窗口位置（紧靠在cmd窗口右侧）
                        window_x = right  # 可以根据需要调整间距
                        window_y = top
                        #
                        if window_x + window_width > wid:
                            window_x = left - window_width - 10
                        # 设置Tkinter窗口大小和位置
                        self.root.geometry(f"{window_width}x{window_height}+{window_x}+{window_y}")
                        self.root.lift()


                    else:
                        tkinter.messagebox.showinfo("错误", "cmd 被关闭无法定位")
                        self.root.destroy()
                        return
                except gw.PyGetWindowException:
                    # tkinter.messagebox.showinfo("no")
                    # return
                    ...

    def show(self):
        self.root.mainloop()

    def run(self):
        self.show()


def new():
    time.sleep(0.2)
    win = UiWindow()
    win.run()

new()